// import Axios, { AxiosResponse } from 'axios'
// // import qs from 'qs'

//

// export const CONTENT_TYPE = 'Content-Type'

// export const FORM_URLENCODED = 'application/x-www-form-urlencoded; charset=UTF-8'

// export const APPLICATION_JSON = 'application/json; charset=UTF-8'

// export const TEXT_PLAIN = 'text/plain; charset=UTF-8'

// const service = Axios.create({
//   baseURL,
//   timeout: 10 * 60 * 1000,
//   withCredentials: true, // 跨域请求时发送cookie
// })

// service.interceptors.request.use(
//   (config) => {
//     !config.headers && (config.headers = {})
//     if (!config.headers[CONTENT_TYPE]) {
//       config.headers[CONTENT_TYPE] = APPLICATION_JSON
//     }
//     if (config.headers[CONTENT_TYPE] === FORM_URLENCODED) {
//       config.data = config.data.stringify()
//     }
//     return config
//   },
//   (error) => {
//     return Promise.reject(error.response)
//   }
// )

// service.interceptors.response.use(
//   (response) => {
//     if (response.status === 200) {
//       return response
//     } else {
//       throw new Error(response.status.toString())
//     }
//   },
//   (error) => {
//     if (import.meta.env.MODE === 'development') {
//       console.log(error)
//     }
//     return Promise.reject({ code: 500, msg: '服务器异常，请稍后重试…' })
//   }
// )

// export default service


import axios from 'axios'
const apiPrefix = `${import.meta.env.BASE_URL}`
export const api = createApi()
export function createApi(prefix = '', urlPrefix = '') {
  const api = axios.create({
    baseURL: `${apiPrefix}${prefix}`,
    timeout: 10 * 60 * 1000,
    // withCredentials: true, // 跨域请求时发送cookie
  })

  api.interceptors.request.use(cfg => {
    const token = sessionStorage.getItem('token')
    if (token) cfg.headers.Authorization = `Bearer ${token}`
    if (urlPrefix && !cfg.url.startsWith('/')) {
      cfg.url = `${urlPrefix}/${cfg.url}`
    }


    return cfg
  }, Promise.reject)

  api.interceptors.response.use(
    res => {

      const { 'content-type': type } = res.headers
      if (type && type.includes('html')) {
        return Promise.reject(new Error('404'))
      }
      return res.data
    },
    err => {

      let status = 500
      let message = err.message || err.toString()
      if (err.response) {
        const { statusText, data } = err.response
        status = err.response.status
        let text = statusText
        if (data) {
          if (typeof data === 'string') {
            text = data
          } else if (typeof data === 'object') {
            text = data.error || data.message || JSON.stringify(data)
          }
        }
        message = text
      }
      return Promise.reject([status, message].join(': '))
    }
  )

  return api
}
